package com.eyas.software.pattern.eventbus.subscriber.impl;

import com.eyas.software.pattern.eventbus.event.Event;
import com.eyas.software.pattern.eventbus.subscriber.Subscriber;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 方法上带有@Subscriber注解的订阅者
 * 需要重写equals方法和hashcode方法
 */
public class AnnotationSubscriber implements Subscriber {
    private Class<?> eventClass;
    private Method eventMethod;

    public AnnotationSubscriber(Class<?> eventClass, Method eventMethod) {
        this.eventClass = eventClass;
        this.eventMethod = eventMethod;
    }

    @Override
    public void invoke(Event event) {
        int methodParamCount = this.eventMethod.getParameterCount();
        try {
            if (methodParamCount == 0) {

                eventMethod.invoke(eventClass.newInstance());

            } else if (methodParamCount == 1) {
                if (this.eventMethod.getParameterTypes()[0] == event.getEventType()) {
                    eventMethod.invoke(eventClass.newInstance(),event.getEventContent());
                } else {
                    throw new IllegalArgumentException("method的方法参数类型与Event的类型不匹配");
                }
            }else {
                throw new IllegalArgumentException("method的方法参数列表超过1个");
            }
        } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int hashCode() {
        return eventMethod.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (o == null)
            return false;
        if (o.getClass() != AnnotationSubscriber.class)
            return false;
        AnnotationSubscriber target = (AnnotationSubscriber) o;
        //这里主要处理NULL的情况
        if (this.eventMethod == target.eventMethod)
            return true;
        if (this.eventMethod == null)
            return false;
        return this.eventMethod.equals(target.eventMethod);
    }
}
